package com.uinnova.product.eam.web.diagram.peer.impl;

import com.binary.core.io.Resource;
import com.binary.core.io.support.ByteArrayResource;
import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.binary.json.JSON;
import com.binarys.product.rsm.client.RsmClient;
import com.uinnova.product.eam.comm.model.*;
import com.uinnova.product.eam.model.DiagramDirTree;
import com.uinnova.product.eam.model.DiagramQ;
import com.uinnova.product.eam.model.VcDiagramDirInfo;
import com.uinnova.product.eam.model.VcDiagramInfo;
import com.uinnova.product.eam.service.VcBaseConfigSvc;
import com.uinnova.product.eam.service.VcDiagramSvc;
import com.uinnova.product.eam.web.diagram.bean.DiagramDirInfo;
import com.uinnova.product.eam.web.diagram.bean.MyDiagramCdt;
import com.uinnova.product.eam.web.diagram.bean.VcDiagramInfoResultWithTopping;
import com.uinnova.product.eam.web.diagram.peer.DiagramV2Peer;
import com.uinnova.product.eam.web.util.DiagramUtil;
import com.uinnova.product.vmdb.comm.i18n.MessageUtil;
import com.uinnova.product.vmdb.comm.i18n.VerifyType;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.query.CSysUser;
import com.uino.util.sys.SysUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class DiagramV2PeerImpl implements DiagramV2Peer{

	/**
	 * 基线库置顶文件存储路径，在base_config表中的code  ，type=6
	 * */
	private final static String baseLibToppingDiagramPathCfgCode = "baseLibToppingDiagramPath";
	/**
	 * 设计库置顶文件存储路径，在base_config表中的code type =5
	 * */
	private final static String designLibToppingDiagramPathCfgCode = "designLibToppingDiagramPath";

	/**
	 * 设计库置顶文件存储路径，在base_config表中的code type =5
	 * */
	private final static String squareToppingDiagramPathCfgCode = "squareToppingDiagramPathCfgCode";


	@Autowired
	private IUserApiSvc userApiSvc;

	@Autowired
	private VcDiagramSvc diagramSvc;

	@Autowired
	private DiagramUtil diagramUtil;

	/** RSM-SLAVE访问入口 **/
	private String rsmSlaveRoot;

	/** RSM分类代码 **/
	private String rsmClassCode;

	public String getRsmSlaveRoot() {
		return rsmSlaveRoot;
	}

	public void setRsmSlaveRoot(String rsmSlaveRoot) {
		this.rsmSlaveRoot = rsmSlaveRoot;
	}

	public String getRsmClassCode() {
		return rsmClassCode;
	}

	public void setRsmClassCode(String rsmClassCode) {
		this.rsmClassCode = rsmClassCode;
	}

	private RsmClient rsmClient;

	@Autowired
	private VcBaseConfigSvc baseConfigSvc;


	/**可以用于*/
	@Override
	public DiagramDirInfo queryMyDirInfoPageByParentId(Integer pageNum, Integer pageSize, MyDiagramCdt paramCdt) {
		Integer dirType = paramCdt.getDirType();
		String like = paramCdt.getLike();
		Integer type = paramCdt.getType();
		Integer queryType = paramCdt.getQueryType();
		Long tagId = paramCdt.getTagId();
		Long pId = paramCdt.getDirId() == null ? 0L : paramCdt.getDirId();


		SysUser loginUser = SysUtil.getCurrentUserInfo();
		Long userId = loginUser.getId();
		Long domainId = loginUser.getDomainId();
		VcDiagramDir dir = null;
		if(pId != 0){
			dir = diagramSvc.queryDiagramDirById(domainId, pId);
			if(dir == null){
				MessageUtil.throwVerify(VerifyType.NOT_EXIST, "record", dir);
			}
		}
		subDirCreatorAndModifier(dir);

		DiagramDirInfo ret = new DiagramDirInfo();
		CVcDiagram dCdt = new CVcDiagram();
		dCdt.setDirType(dirType);
		if(!BinaryUtils.isEmpty(type) && type == 3){
			//文件夹
			//ret.setChildrenDirs(queryAndFillDiagramDirList(domainId,pId,dirType,like,userId));
		}else{
			dCdt.setUserId(userId);
			dCdt = fillDiagramCdtByTypes(dCdt, like, type, queryType, pId, tagId,new Integer[] {dirType});
			Page<VcDiagramInfo> page = null;
			if(dCdt != null) {
				dCdt.setStatus(1);
				page = diagramSvc.queryDiagramInfoPage(domainId, pageNum, pageSize, dCdt, "MODIFY_TIME DESC" ,new DiagramQ[]{DiagramQ.TAGS,DiagramQ.GROUPS,DiagramQ.CREATOR});
				List<VcDiagramInfo> diagramInfos = page.getData();
				diagramUtil.trimDiagramList(diagramInfos, null);
				ret.setDiagramInfoPage(new Page<VcDiagramInfo>(page.getPageNum(), page.getPageSize(), page.getTotalRows(), page.getTotalPages(), diagramInfos));
			}
			//如果当前页等于最大页码并且type为null或者0时查询目录相关信息
			if( page == null || (pageNum >= page.getTotalPages() && (BinaryUtils.isEmpty(type) || type.intValue() == 0)) &&  queryType.equals(0)) {
				//ret.setChildrenDirs(queryAndFillDiagramDirList(domainId,pId,dirType,like,userId));
			}
		}
		List<VcDiagramDir> childrenDirs = ret.getChildrenDirs();
		if(!BinaryUtils.isEmpty(childrenDirs)) {
			Set<Long> dirIds = new HashSet<Long>();
			for(VcDiagramDir childrenDir : childrenDirs) {
				dirIds.add(childrenDir.getId());
			}
			ret.setDirDiagramCountMap(queryDirDiagramCount(domainId,null,dirIds.toArray(new Long[0]),userId,dirType));
		}
		Page<VcDiagramInfo> infoPage = ret.getDiagramInfoPage();

		if(!BinaryUtils.isEmpty(infoPage) && !BinaryUtils.isEmpty(infoPage.getData())) {
			List<VcDiagramInfo> ds = infoPage.getData();

			Set<Long> ids = new HashSet<Long>();
			for(VcDiagramInfo info : ds ) {
				ids.add(info.getDiagram().getId());
			}
		}
		if(dCdt !=null && ( BinaryUtils.isEmpty(type) || !type.equals(3) && (BinaryUtils.isEmpty(pId) || pId.equals(0L)))) {
			//查询我已提交的视图()和我需要操作的视图
			MyDiagramCdt myDCdt = new MyDiagramCdt();
			myDCdt.setName(dCdt.getName());
			myDCdt.setDiagramTypes(dCdt.getDiagramTypes());
			myDCdt.setIds(dCdt.getIds());
			myDCdt.setUserIds(dCdt.getUserIds());

		}
		ret.setDiagramDir(dir);
		return ret;
	}

	/**
	 * 根据类型填充视图查询对象
	 * @param cdt 一定要初始化
	 * @param like 关键字
	 * @param type 1=单图  2=组合视图  4=模板  其他为全部
	 * @param queryType 0=名称 1=作者 2=标签 3=ci
	 * @param pId 目录id
	 * @param tagId 标签ID
	 * @return
	  */
	private CVcDiagram fillDiagramCdtByTypes(CVcDiagram cdt ,String like,Integer type,Integer queryType,Long pId,Long tagId,Integer[] dirTypes) {
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
		String word = null;
		if(!BinaryUtils.isEmpty(like, true)){
			word = new String(like);
			like = "%" + like + "%";
		}
		Set<Long> dirTypeDiagramIds = new HashSet<Long>();
		//TODO
		cdt.setDirTypes(dirTypes);
		List<Integer> list = Arrays.asList(dirTypes);
		if(!dirTypes[0].equals(1) && (!list.contains(5) || !list.contains(6))) {
			//查询目录和视图的关联关系
			CVcDiagramDirRelation reltCdt = new CVcDiagramDirRelation();
			if(pId.intValue() == 0 && !BinaryUtils.isEmpty(like)){
				reltCdt.setDirId(pId);
			}
			reltCdt.setDomainId(domainId);
			reltCdt.setDirTypes(dirTypes);
			Map<Long, Set<Long>> map = diagramSvc.queryDiagramDirRelation(domainId, reltCdt);
			if(BinaryUtils.isEmpty(map)) return null;

			for(Map.Entry<Long, Set<Long>> entry : map.entrySet()) {
				dirTypeDiagramIds.addAll(entry.getValue());
			}

		}
		if(BinaryUtils.isEmpty(type) && !type.equals(3)){
			cdt.setDomainId(domainId);
			//当没有进入子目录的时候不需要按照文件夹
			if(pId.intValue() == 0 && !BinaryUtils.isEmpty(like)){
				cdt.setDirId(null);
			}
			cdt.setStatus(1);
			if(!BinaryUtils.isEmpty(type) && type.intValue() == 1){
				//单图
				cdt.setDiagramTypes(new Integer[]{1});
			}else if(!BinaryUtils.isEmpty(type) && type.intValue() == 2){
				//组合视图
				cdt.setDiagramTypes(new Integer[]{2});
			}else if(!BinaryUtils.isEmpty(type) && type.intValue() == 4){
				//模版
				cdt.setDiagramTypes(new Integer[]{3});
			}else{
				//全部
				cdt.setDiagramTypes(new Integer[]{1,2,3});
			}
		}
		//查询类型
		if(BinaryUtils.isEmpty(queryType)) queryType = 0;
		if(queryType.intValue() == 0){ //名称查询
			if(like != null){
				cdt.setName(like);
			}
		} else if(queryType.intValue() == 1){ //通过作者查询
			if(!BinaryUtils.isEmpty(like)) {
				CSysUser cSysUser = new CSysUser();
				cSysUser.setDomainId(domainId);
				cSysUser.setSuperUserFlags(new Integer[]{0,1});
				List<SysUser> sysUserByCdt = userApiSvc.getSysUserByCdt(cSysUser);
				Set<Long> userIdSet = new HashSet<>();
				for (SysUser sysUser : sysUserByCdt) {
					userIdSet.add(sysUser.getId());
					sysUser.setLoginPasswd(null);
				}
				if(userIdSet.size() == 0) {
					return null;
				} else {
					cdt.setUserId(null);
					cdt.setUserIds(userIdSet.toArray(new Long[0]));
				}
			}
		}

		if(!BinaryUtils.isEmpty(cdt.getIds())) {
			 dirTypeDiagramIds.retainAll(Arrays.asList(cdt.getIds()));
			 if(BinaryUtils.isEmpty(dirTypeDiagramIds)) return null;
		}
		cdt.setIds(dirTypeDiagramIds.toArray(new Long[0]));
		return cdt;
	}

	private void subDirCreatorAndModifier(VcDiagramDir diagramDir) {
		if(diagramDir != null) {
			diagramDir.setCreator(subName(diagramDir.getCreator()));
			diagramDir.setModifier(subName(diagramDir.getModifier()));
		}
	}

	@SuppressWarnings("unused")
	private List<VcDiagramDir> queryAndFillDiagramDirList(Long domainId, Long pId,Integer dirType, String like, Long userId){
		CVcDiagramDir cdt = new CVcDiagramDir();
		cdt.setParentId(pId);
		cdt.setUserId(userId);
		if(like != null){
			cdt.setDirName(like);
		}
		cdt.setDomainId(domainId);
		cdt.setDirType(dirType);
		List<VcDiagramDir> queryDiagramDirList = diagramSvc.queryDiagramDirList(domainId, cdt, "MODIFY_TIME DESC");

		subListDirCreatorAndModifier(queryDiagramDirList);
		return queryDiagramDirList;
	}

	/**
	 * 将创建者和修改者名字剪切掉 aa[bb] --> aa
	 * @param diagramInfo 视图信息
	 */
	private void subCreatorAndModifier(VcDiagramInfo diagramInfo){
		if(diagramInfo != null){
			VcDiagram diagram = diagramInfo.getDiagram();
			if(diagram != null){
				diagram.setCreator(subName(diagram.getCreator()));
				diagram.setModifier(subName(diagram.getModifier()));
			}
		}
	}

	private void subListDirCreatorAndModifier(List<VcDiagramDir> diagramDirs) {
		if(diagramDirs != null) {
			for (VcDiagramDir diagramDir : diagramDirs) {
				subDirCreatorAndModifier(diagramDir);
			}
		}
	}

	private String subName(String name){
		if(name != null){
			int lastIndexOf = name.lastIndexOf("[");
			if(lastIndexOf > 0){
				return	name.substring(0, lastIndexOf);
			}
		}
		return name;
	}

	private Map<Long,Integer> queryDirDiagramCount(Long domainId,CVcDiagram dCdt ,Long[] dirIds,Long userId,Integer dirType){
		Map<Long,Integer> map = new HashMap<Long,Integer>();
		if(dirType!= null && dirType.equals(1)) {
			List<VcDiagramDirInfo> list = diagramSvc.queryDirDiagramCountList(domainId, dirIds, userId);
			if(BinaryUtils.isEmpty(list)) return map;

			for(VcDiagramDirInfo dirInfo : list) {
				map.put(dirInfo.getDirId(), dirInfo.getDiagramCount() == null? 0 : dirInfo.getDiagramCount());
			}
		}else {
			CVcDiagramDirRelation cdt = new CVcDiagramDirRelation();
			cdt.setDirIds(dirIds);
			cdt.setDirType(dirType);
			Map<Long, Set<Long>> reltMp = diagramSvc.queryDiagramDirRelation(domainId, cdt);
			if(BinaryUtils.isEmpty(reltMp)) {
				return map;
			}
			Set<Long> dids = new HashSet<Long>();
			for(Map.Entry<Long, Set<Long>> entry : reltMp.entrySet()) {
				dids.addAll(entry.getValue());
			}
			if(dCdt == null) dCdt = new CVcDiagram();
			dCdt.setStatus(1);
			dCdt.setIds(dids.toArray(new Long[0]));
			List<VcDiagram> list = diagramSvc.queryDiagramList(domainId, dCdt, null);
			if(BinaryUtils.isEmpty(list)) return map;
			Map<Long, VcDiagram> idDiagramMap = BinaryUtils.toObjectMap(list, "id");
			for(Map.Entry<Long, Set<Long>> entry : reltMp.entrySet()) {
				Set<Long> value = entry.getValue();
				Integer count = 0;
				for(Long id : value) {
					if(!BinaryUtils.isEmpty(idDiagramMap.get(id))) count ++;
				}
				map.put(entry.getKey(), count);
			}
		}
		return map;
	}

	@Override
	public DiagramDirTree queryDiagramTree(Long processId, Integer dirType, Integer queryType, String like, Long dirUserId) {
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
		Long userId = SysUtil.getCurrentUserInfo().getId();
		CVcDiagram dCdt = new CVcDiagram();
		if(!BinaryUtils.isEmpty(dirUserId)) {
			userId = dirUserId;
		}else {
			dCdt.setUserId(userId);
		}

		String word = null;
		if(!BinaryUtils.isEmpty(like, true)){
			word = new String(like);
			like = "%" + like + "%";
		}
		if(BinaryUtils.isEmpty(queryType)) queryType = 0;
		//前面是否查询到视图id
		boolean flag = true;
		if(queryType.intValue() == 0){ //名称查询
			if(like != null){
				dCdt.setName(like);
			}
		}
		return diagramSvc.queryDiagramTreeByDirRelation(domainId,userId,dirType,dCdt, null,flag);
	}

	@Override
	public DiagramDirInfo queryShowDiagramInfoPage(Integer pageNum, Integer pageSize, MyDiagramCdt paramCdt, String orders) {
		String like = paramCdt.getLike();
		Integer type = paramCdt.getType();
		Integer queryType = paramCdt.getQueryType();
		Long tagId = paramCdt.getTagId();


		SysUser loginUser = SysUtil.getCurrentUserInfo();
		Long userId = loginUser.getId();
		Long domainId = loginUser.getDomainId();

		DiagramDirInfo ret = new DiagramDirInfo();

		CVcDiagram dCdt = new CVcDiagram();
		if(!BinaryUtils.isEmpty(type) && type == 3){
			//文件夹
			//ret.setChildrenDirs(queryAndFillDiagramDirList(domainId,pId,dirType,like,userId));
		}else{
			dCdt.setUserId(userId);
			dCdt = fillDiagramCdtByTypes(dCdt, like, type, queryType, 0L, tagId,new Integer[] {5,6});
			Page<VcDiagramInfo> page = null;
			if(dCdt != null) {
				dCdt.setStatus(1);
				page = diagramSvc.queryDiagramInfoPage(domainId, pageNum, pageSize, dCdt, orders ,new DiagramQ[]{DiagramQ.TAGS,DiagramQ.GROUPS,DiagramQ.CREATOR});
				List<VcDiagramInfo> diagramInfos = page.getData();
				diagramUtil.trimDiagramList(diagramInfos, null);
				ret.setDiagramInfoPage(new Page<VcDiagramInfo>(page.getPageNum(), page.getPageSize(), page.getTotalRows(), page.getTotalPages(), diagramInfos));
			}
			//如果当前页等于最大页码并且type为null或者0时查询目录相关信息
			if( page == null || (pageNum >= page.getTotalPages() && (BinaryUtils.isEmpty(type) || type.intValue() == 0)) &&  queryType.equals(0)) {
				//ret.setChildrenDirs(queryAndFillDiagramDirList(domainId,pId,dirType,like,userId));
			}
		}
		Page<VcDiagramInfo> infoPage = ret.getDiagramInfoPage();

		if(!BinaryUtils.isEmpty(infoPage) && !BinaryUtils.isEmpty(infoPage.getData())) {
			List<VcDiagramInfo> ds = infoPage.getData();

			Map<Integer,Set<Long>> dirTypeDiagramIdsMap = new HashMap<Integer,Set<Long>>();
			Map<Integer,Set<VcDiagramInfo>> dirTypeDiagramsMap = new HashMap<Integer,Set<VcDiagramInfo>>();
			for(VcDiagramInfo info : ds ) {
				Integer dirType = info.getDiagram().getDirType();
				Set<Long> idSet = dirTypeDiagramIdsMap.get(dirType);
				Set<VcDiagramInfo> diagramSet = dirTypeDiagramsMap.get(dirType);
				if(idSet == null) {
					idSet = new HashSet<Long>();
					diagramSet = new HashSet<VcDiagramInfo>();
					dirTypeDiagramIdsMap.put(dirType, idSet);
					dirTypeDiagramsMap.put(dirType, diagramSet);
				}
				idSet.add(info.getDiagram().getId());
				diagramSet.add(info);
			}

		}
		if(dCdt !=null && ( BinaryUtils.isEmpty(type) || !type.equals(3))) {
			List<VcDiagramInfo> needMeOpDiagrams = new ArrayList<VcDiagramInfo>();
			List<VcDiagramInfo> myOpDiagramsNotMine = new ArrayList<VcDiagramInfo>();
			Set<Long> diagramIds = new HashSet<Long>();

			List<VcDiagramInfo> needMeOpDiagramsRes = new ArrayList<VcDiagramInfo>();
			List<VcDiagramInfo> myOpDiagramsNotMineRes = new ArrayList<VcDiagramInfo>();
			for(VcDiagramInfo info : needMeOpDiagrams) {
				Long id = info.getDiagram().getId();
				if(diagramIds.contains(id)) continue;
				diagramIds.add(id);
				needMeOpDiagramsRes.add(info);
			}
			for(VcDiagramInfo info : myOpDiagramsNotMine) {
				Long id = info.getDiagram().getId();
				if(diagramIds.contains(id)) continue;
				diagramIds.add(id);
				myOpDiagramsNotMineRes.add(info);
			}
			diagramUtil.trimDiagramList(needMeOpDiagramsRes, null);
			diagramUtil.trimDiagramList(myOpDiagramsNotMineRes, null);
			ret.setNeedMeOpDiagrams(needMeOpDiagramsRes);
			ret.setMyOpDiagramsNotMine(myOpDiagramsNotMineRes);
		}
		return ret;
	}


	@Override
	public VcDiagramInfoResultWithTopping queryDiagramInfoPageWithTopping(Integer pageNum, Integer pageSize, MyDiagramCdt cdt, String orders, String token){
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();

		VcDiagramInfoResultWithTopping result = new VcDiagramInfoResultWithTopping();
		Integer queryType = cdt.getQueryType();   //查询类型
		Integer type = cdt.getType();		//筛选类型
		Long tagId = cdt.getTagId();	//tagId
		String like = cdt.getLike();	//搜索
		Long dirId = cdt.getDirId();
		Integer dirType = cdt.getDirType();   //dirType = 5 设计库  dirType=6 基线库

		String word = null;
		if(!BinaryUtils.isEmpty(like, true)){
			word = new String(like);
			like = "%" + like + "%";
		}

		VcDiagramDir dir = null;
		if(dirId != null && dirId != 0){
			dir = diagramSvc.queryDiagramDirById(domainId, dirId);
			if(dir == null){
				MessageUtil.throwVerify(VerifyType.NOT_EXIST, "record", dir);
			}
		}
		subDirCreatorAndModifier(dir);

		if(!BinaryUtils.isEmpty(type) && type == 3){
		}else{
			CVcDiagram dCdt = new CVcDiagram();
			dCdt.setDomainId(domainId);
			//dCdt.setDirId(dirId);
			dCdt.setDirType(dirType);

			dCdt.setStatus(1);
			if(!BinaryUtils.isEmpty(type) && type.intValue() == 1){
				//单图
				dCdt.setDiagramTypes(new Integer[]{1});
			}else if(!BinaryUtils.isEmpty(type) && type.intValue() == 2){
				//组合视图

				dCdt.setDiagramTypes(new Integer[] {2});
			}else if(!BinaryUtils.isEmpty(type) && type.intValue() == 4){
				//模版
				dCdt.setDiagramTypes(new Integer[]{3});
			}else{
				//全部
				dCdt.setDiagramTypes(new Integer[]{1,2,3});
			}

			//查询类型
			if(BinaryUtils.isEmpty(queryType)) queryType = 0;
			if(queryType.intValue() == 0){ //名称查询
				if(like != null){
					dCdt.setName(like);
				}
			}else if(queryType.intValue() == 1){ //通过作者查询
				if(!BinaryUtils.isEmpty(like)) {
//					List<SysOp> queryList = opSvc.queryList(domainGetter.getDomainId(), domainId, opcdt, "");
					CSysUser cSysUser = new CSysUser();
					cSysUser.setDomainId(domainId);
//					cSysUser.setOpName(like);
					cSysUser.setSuperUserFlags(new Integer[]{0,1});
					List<SysUser> sysUsers = userApiSvc.getSysUserByCdt(cSysUser);
					Set<Long> userIdSet = new HashSet<>();
					for (SysUser sysUser : sysUsers) {
						userIdSet.add(sysUser.getId());
						sysUser.setLoginPasswd(null);
					}
					if(userIdSet.size() == 0) {
						return result;
					} else {
						dCdt.setUserIds(userIdSet.toArray(new Long[0]));
					}
				}
			}
			//查询目录所在视图
			if(!BinaryUtils.isEmpty(dirId)) {
				Long[] ids = dCdt.getIds();
				CVcDiagramDirRelation relationCdt = new CVcDiagramDirRelation();
				relationCdt.setDirId(dirId);
				relationCdt.setDirType(dirType);
				Map<Long, Set<Long>> map = diagramSvc.queryDiagramDirRelation(domainId, relationCdt);
				if(BinaryUtils.isEmpty(map)) return result;
				Set<Long> dirDiagramIds = map.get(dirId);
				if(!BinaryUtils.isEmpty(ids)) {
					List<Long> list = Arrays.asList(ids);
					list.retainAll(dirDiagramIds);
					if(BinaryUtils.isEmpty(list)) return result;
					dCdt.setIds(list.toArray(new Long[0]));
				}else {
					dCdt.setIds(dirDiagramIds.toArray(new Long[0]));
				}
			}

			List<Long> list = getToppingDiagramIds(dirType, token);   //当前用户置顶的视图id
			Long[] notInIds = null;

			List<VcDiagramInfo> toppingDiagrams = new ArrayList<VcDiagramInfo>();
			if(!BinaryUtils.isEmpty(list)) {
				notInIds = list.toArray(new Long[0]);
				List<VcDiagramInfo> diagramInfos = diagramSvc.queryDiagramInfoList(domainId, dCdt, orders, cdt.getDiagramQs());
				diagramUtil.trimDiagramList(diagramInfos, null);
				if(!BinaryUtils.isEmpty(diagramInfos)) {
					Map<Long,VcDiagramInfo> idDiagramInfoMap = new HashMap<Long,VcDiagramInfo>();
					for(VcDiagramInfo diagramInfo : diagramInfos) {
						fillPath(diagramInfo);
						subCreatorAndModifier(diagramInfo);
						idDiagramInfoMap.put(diagramInfo.getDiagram().getId(), diagramInfo);
					}
					for(Long id : list) {
						VcDiagramInfo info = idDiagramInfoMap.get(id);
						if(!BinaryUtils.isEmpty(info )) toppingDiagrams.add(info);
					}
				}
			}
			//查询非置顶视图
			Page<VcDiagramInfo> page = diagramSvc.queryDiagramPageByCdtAndNotInIds(domainId, pageNum, pageSize, dCdt, notInIds, orders,cdt.getDiagramQs());
			diagramUtil.trimDiagramList(page.getData(), null);
			result.setDiagramPageInfos(page);
			//fillProcessNodeInfos(dirType,page.getData());
			result.setToppingDiagrams(toppingDiagrams);
			//fillProcessNodeInfos(dirType,toppingDiagrams);
		}

		return result;
	}

	//type 6=基线库，5=设计库
	@SuppressWarnings("rawtypes")
	@Override
	public List<Long> getToppingDiagramIds(Integer type ,String token){
		if(type == null) return new ArrayList<Long>();
		Long userId = SysUtil.getCurrentUserInfo().getId();
		String cfgCode = null;
		if(type.equals(6))
			cfgCode = baseLibToppingDiagramPathCfgCode;
		else if(type.equals(5))
			cfgCode = designLibToppingDiagramPathCfgCode;
		else if(type.equals(7)) {
			userId = getAdminUserId();
			cfgCode = squareToppingDiagramPathCfgCode;
		}
		
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
		String toppingDiagramPath = baseConfigSvc.queryCfgContentByCode(domainId, cfgCode);
		if(BinaryUtils.isEmpty(toppingDiagramPath)) return null;
		
		Resource resource = rsmClient.getResource(toppingDiagramPath, token);
		String content = null;
		try {
			content = IOUtils.toString(resource.getInputStream(), "utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		Map map = (Map)JSON.toObject(content);
		String diagramIdOrder = (String)map.get(userId+"");
		List<Long> diagramIds = idsStrToIdSet(diagramIdOrder);
		if(getViewPermissionStatus()&&diagramIds!=null&&diagramIds.size()>0) {
			// TODO roleApi替换
			Set<Long> userIds = new HashSet<>();//roleOrgPeer.querySeeUserIdsByCurrentUserRoleOrg();


			if(userIds==null||userIds.size()<=0){
				//代表他谁的也看不了，也就不需要判断了
				return new ArrayList<>();
			}
			CVcDiagram cdt=new CVcDiagram();
			cdt.setIds(diagramIds.toArray(new Long[diagramIds.size()]));
			cdt.setUserIds(userIds.toArray(new Long[userIds.size()]));
			List<VcDiagram> diagrams=diagramSvc.queryDiagramList(domainId, cdt, null);
			Set<Long> hasSeeAuthDiagramIds=new HashSet<>();
			if(diagrams!=null&&diagrams.size()>0){
				for(VcDiagram diagram:diagrams){
					hasSeeAuthDiagramIds.add(diagram.getId());
				}
			}
			List<Long> returnDiagramIds=new LinkedList<>();
			for(Long diagramId:diagramIds){
				if(hasSeeAuthDiagramIds.contains(diagramId)){
					returnDiagramIds.add(diagramId);
				}
			}
			return returnDiagramIds;
		}
		return diagramIds;
//		if(getViewPermissionStatus()&&diagramIds!=null&&diagramIds.size()>0){
//			List<Long> returnDiagramIds=new LinkedList<>();
//			Map<Long, DiagramAuth> authMap=	diagramPeer.getDiagramAuth(diagramIds);
//			if(authMap!=null){			
//				for (Long diagramId : diagramIds) {
//					if(authMap.get(diagramId)!=null&&authMap.get(diagramId).isSee())returnDiagramIds.add(diagramId);
//				}
//			}
//			return returnDiagramIds;
//		}else{
//			return 	diagramIds;
//		}
	}

	@Override
	public List<VcDiagramInfo> getToppingDiagramInfos(Integer type, String token){
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
		List<Long> diagramIds = getToppingDiagramIds(type,token);
		if(BinaryUtils.isEmpty(diagramIds)) return new ArrayList<>();

		CVcDiagram diagramCdt = new CVcDiagram();
		diagramCdt.setIsOpen(1);
		diagramCdt.setIds(diagramIds.toArray(new Long[0]));
		diagramCdt.setStatus(1);
		List<VcDiagramInfo> vcDiagramInfos = diagramSvc.queryDiagramInfoList(domainId, diagramCdt, null, new DiagramQ[]{DiagramQ.TAGS, DiagramQ.CREATOR, DiagramQ.GROUPS});

		diagramUtil.trimDiagramList(vcDiagramInfos, null);


		//组合视图的缩略图重组
		diagramUtil.fillCombs(vcDiagramInfos, false, null);
		//根据ids排序
        Map<Long,VcDiagramInfo> map = new HashMap<>();
        for(VcDiagramInfo diagramInfo : vcDiagramInfos){
            map.put(diagramInfo.getDiagram().getId(),diagramInfo);
        }
        List<VcDiagramInfo> res = new ArrayList<>();
        for(Long id : diagramIds){
            VcDiagramInfo diagramInfo = map.get(id);
            if(!BinaryUtils.isEmpty(diagramInfo)) res.add(diagramInfo);
        }
		return res;
	}
	
	private Long getAdminUserId() {
		CSysUser cSysUser = new CSysUser();
		cSysUser.setLoginCode("admin");
		cSysUser.setSuperUserFlags(new Integer[]{0,1});
		List<SysUser> sysUserByCdt = userApiSvc.getSysUserByCdt(cSysUser);
		return sysUserByCdt.get(0).getId();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public synchronized Integer toppingDiagramById(Long id,Integer dirType,String token) {
		Long userId = SysUtil.getCurrentUserInfo().getId();
		String cfgCode = null;
		if(dirType.equals(6))
			cfgCode = baseLibToppingDiagramPathCfgCode;
		else if(dirType.equals(5))
			cfgCode = designLibToppingDiagramPathCfgCode;
		else if(dirType.equals(7)) {
			cfgCode = squareToppingDiagramPathCfgCode;
			userId = getAdminUserId();
		}
		
		MessageUtil.checkEmpty(id, "id");
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
		String toppingDiagramPath = baseConfigSvc.queryCfgContentByCode(domainId, cfgCode);
		if(BinaryUtils.isEmpty(toppingDiagramPath)) {
			toppingDiagramPath = saveOrUpdateRes(toppingDiagramPath, cfgCode+".json", "{}", token);
			VcBaseConfig baseConfig = new VcBaseConfig();
			baseConfig.setCfgCode(cfgCode);
			baseConfig.setCfgContent(toppingDiagramPath);
			baseConfig.setDomainId(domainId);
			baseConfigSvc.saveOrUpdateBaseConfig(domainId, baseConfig);
		}
		Resource resource = rsmClient.getResource(toppingDiagramPath, token);
		String content = null;
		try {
			content = IOUtils.toString(resource.getInputStream(), "utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		//存储的数据：{userId:1001,1002,1003}
		
		Map map = (Map)JSON.toObject(content);
		String diagramIdOrder = (String)map.get(userId+"");
		if(BinaryUtils.isEmpty(diagramIdOrder)) map.put(userId+"", id+",");
		else {
			if(diagramIdOrder.contains(id+",")) {
				diagramIdOrder = diagramIdOrder.replaceAll(id+",", "");
			}
			List<Long> list = idsStrToIdSet(diagramIdOrder);
			//截取超过50的部分
			if(list.size()>50) {
				String str1 = diagramIdOrder.substring(0, diagramIdOrder.length()-1);
				diagramIdOrder = str1.substring(0,str1.lastIndexOf(","))+",";
			} 
			diagramIdOrder  = id+ "," + diagramIdOrder;
			map.put(userId+"", diagramIdOrder);
		}
		saveOrUpdateRes(toppingDiagramPath, cfgCode+".json", JSON.toString(map), token);
		return 1;
	}
	//type 3=基线库，2=设计库
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public synchronized Integer removeToppingDiagramIds(Long[] ids,Integer[] types,String token) {
		
		for(Integer type : types) {
			Long userId = SysUtil.getCurrentUserInfo().getId();
			String cfgCode = null;
			if(type.equals(6))
				cfgCode = baseLibToppingDiagramPathCfgCode;
			else if(type.equals(5))
				cfgCode = designLibToppingDiagramPathCfgCode;
			else if(type.equals(7)) {
				cfgCode = squareToppingDiagramPathCfgCode;
				userId = getAdminUserId();
			}
			
			
			Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
			String toppingDiagramPath = baseConfigSvc.queryCfgContentByCode(domainId, cfgCode);
			if(BinaryUtils.isEmpty(toppingDiagramPath)) continue;
			
			Resource resource = rsmClient.getResource(toppingDiagramPath, token);
			String content = null;
			try {
				content = IOUtils.toString(resource.getInputStream(), "utf-8");
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
			Map map = (Map)JSON.toObject(content);
			String diagramIdOrder = (String)map.get(userId+"");
			if(BinaryUtils.isEmpty(diagramIdOrder)) continue;
			for(Long id : ids) {
				if(diagramIdOrder.contains(id+",")) {
					diagramIdOrder = diagramIdOrder.replaceAll(id+",", "");
				}
			}
			map.put(userId+"", diagramIdOrder);
			saveOrUpdateRes(toppingDiagramPath, cfgCode+".json", JSON.toString(map), token);
		}
		
		return 1;
		
	}
	
	private void fillPath(VcDiagramInfo diagramInfo) {
		if(diagramInfo == null) return;
		VcDiagram diagram = diagramInfo.getDiagram();
		if(diagram == null) return;
		
		//缩略图
		String icon1 = diagram.getIcon1();
		if(icon1 != null && !icon1.startsWith(rsmSlaveRoot)){
			icon1 = rsmSlaveRoot + icon1;
			diagram.setIcon1(icon1);
		}
		
		String diagramBgImg = diagram.getDiagramBgImg();
		if(diagramBgImg !=null && !BinaryUtils.isEmpty(diagramBgImg.trim()) && !diagramBgImg.startsWith(rsmSlaveRoot)) {
			diagramBgImg = rsmSlaveRoot + diagramBgImg ;
			diagram.setDiagramBgImg(diagramBgImg);
		}
		
		
		List<VcGroup> groups = diagramInfo.getGroups();
		if (!BinaryUtils.isEmpty(groups)) {
			for (VcGroup vcGroup : groups) {
				String groupImage = vcGroup.getGroupImage();
				if (!BinaryUtils.isEmpty(groupImage) && !groupImage.startsWith(rsmSlaveRoot)) {
					groupImage = rsmSlaveRoot + groupImage;
				}
				vcGroup.setGroupImage(groupImage);
				subGroupCreatorAndModifier(vcGroup);
			}
		}
		//修整用户头像信息
		SysUser creator = diagramInfo.getCreator();
		// TODO custom3
//		if(creator != null){
//			String custom3 = creator.getCustom3();
//			//这儿判断是因为当前用户是同一个对象，所以再修改会无限拼接，勿删！！！！！！
//			if(custom3 != null && !custom3.startsWith(this.rsmSlaveRoot)){
//				creator.setCustom3(rsmSlaveRoot+custom3);
//			}
//		}
	}
	private String saveOrUpdateRes(String path, String name, String content, String token) {
		try {
			ByteArrayResource resource = toResource(content, name);
			if (path == null) {
				return rsmClient.saveResource(resource, this.rsmClassCode,
						token);
			} else {
				path = subRsmSlaveRoot(path);
				rsmClient.replaceResource(resource, path, token);
			}
		} catch (Exception e) {
			//removeRes(path, token);
 		}
		return path;
	}
	private ByteArrayResource toResource(String content,String resourceName){
		try {
			return new ByteArrayResource(content.getBytes("utf-8"), resourceName);
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}
	private String subRsmSlaveRoot(String url) {
		if(!BinaryUtils.isEmpty(url) && url.startsWith(rsmSlaveRoot)){
			return url.substring(rsmSlaveRoot.length(), url.length());
		}
		return url;
	}
	
	private List<Long> idsStrToIdSet(String str){
		List<Long> ids = new ArrayList<Long>();
		if(!BinaryUtils.isEmpty(str)){
			String[] strs = str.split(",");
			for(String idStr : strs){
				try {
					ids.add(Long.parseLong(idStr));
				} catch (Exception e) {
				}
				
			}
		} 
		return ids;
	}
	private void subGroupCreatorAndModifier(VcGroup group){
		if(group != null) {
			group.setModifier(subName(group.getModifier()));
			group.setCreator(subName(group.getCreator()));
		}
	}
	
	private Boolean getViewPermissionStatus() {
		//视图权限是否走所属组织
		String viewPermission = baseConfigSvc.queryCfgContentByCode(SysUtil.getCurrentUserInfo().getDomainId(), "viewPermission");
		Boolean res = false;
		if(!BinaryUtils.isEmpty(viewPermission)) {
			if("1".equals(viewPermission)) res = true;
		}
		return res;
	}
}
